﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RAP.Framework.Libary.DataSource.Model.Attribute;
using RAP.Framework.Libary.Utils;

namespace RAP.Framework.Libary.DataSource.Model.DataSource
{
  /// <summary>
  /// 
  /// </summary>
  public class DataSourceOption
  {
    private static int _dataSourceOptionUniqueId = 0;
    /// <summary>
    /// 
    /// </summary>
    public DataSourceOption() { }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="config"></param>
    public DataSourceOption(IDictionary config)
    {
      config.CopyToObject(this);
      if (Name.IsNullOrEmpty())
      {
        Interlocked.Increment(ref _dataSourceOptionUniqueId);
        Name = $"DataSourceOption_{_dataSourceOptionUniqueId}";
      }
    }

    /// <summary>
    /// 数据源名称，在当前数据源分组中不能重复
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 数据驱动Id
    /// </summary>
    public string Provider { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public string ConnectionString { get; set; }

    /// <summary>
    /// 数据库连接字符串是否加密了
    /// </summary>
    public bool Encrypted { get; set; }

    /// <summary>
    /// 数据库连接驱动的类型
    /// </summary>
    public string ConnectionType { get; internal set; }

    /// <summary>
    /// 数据源Id
    /// </summary>
    public string DataSourceId { get; set; }

    /// <summary>
    /// SQl语法兼容类型（Sqlserver、MySQL）
    /// </summary>
    public string SqlGrammar {  get; set; }

    /// <summary>
    /// 是否已初始化
    /// </summary>
    public bool Initialized { get; set; }

    /// <summary>
    /// 测试数据库连接
    /// </summary>
    /// <returns></returns>
    public bool TestConnection()
    {
      var conn = CreateConnection();
      try
      {
        conn.Open();
        return true;
      }
      catch
      {
        return false;
      }
    }

    /// <summary>
    /// 创建数据库连接对象
    /// </summary>
    public IDbConnection CreateConnection()
    {
      if (!Initialized)
      {
        throw new Exception($"数据源配置对象：{DataSourceId}-{Name} 未初始化！");
      }
      var conn = ConnectionType.CreateInstance<IDbConnection>();
      conn.ConnectionString = ConnectionString;
      return conn;
    }

  }
}
